<template>
  <div class="avatar-uploader">
    <mu-sub-header>头像上传</mu-sub-header>
    <avatar-input ref="avatarInput" v-model="avatar" />
    <mu-button v-if="avatar !== null" color="success" full-width @click="upload()">确定上传</mu-button>
  </div>
</template>

<script>
import AvatarInput from '@/components/AvatarInput'
import { mapGetters } from 'vuex'
import api from '@/api'

export default {
  name: 'AvatarUploader',
  components: {
    AvatarInput
  },
  data() {
    return {
      avatar: null
    }
  },
  computed: {
    ...mapGetters({
      isPhone: 'isPhone'
    })
  },
  methods: {
    // 上传头像
    async upload() {
      try {
        await api.uploadAvatar(this.avatar)
        this.$toast.success('头像上传成功')
        this.$refs.avatarInput.removeImage()
        this.$emit('refresh')
      } catch (err) {
        this.$apiCatch(err)
      }
    }
  }
}
</script>

<style scoped>
.avatar-img {
  display: block;
  width: 200px;
  height: 200px;
  object-fit: contain;
  border-radius: 50%;
}

.is-phone .avatar-uploader {
  padding: 12px 20px;
}
.is-phone .avatar-input {
  margin: 0 auto;
}
</style>
